<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\order\Vip;
use app\admin\model\Third;
use app\admin\model\topic\Topic;
use app\admin\model\topic\Type;
use app\admin\model\UserFind;
use app\common\controller\Api;
use fast\Date;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function pay()
    {
        $amount = $this->request->request('amount');
        $type = $this->request->request('type');
        $method = $this->request->request('method');
        $vipType = $this->request->request('vipType');

        if (!$amount || $amount < 0) {
            $this->error("支付金额必须大于0");
        }

        if (!$type || !in_array($type, ['alipay', 'wechat'])) {
            $this->error("支付类型不能为空");
        }

        //订单号
        $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);

        //订单标题
        $title = '会员订单';

        //生成订单
        $model = new Vip();

        $model->user_id = $this->auth->id;
        $model->order_no = 'gpt'.$out_trade_no;
        $model->price = $amount;
        $model->type = $vipType;
        $model->out_trade_no = $out_trade_no;
        $model->save();

        //回调链接
        $notifyurl = $this->request->root(true) . '/addons/epay/index/notifyx/paytype/' . $type;
        $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;

        $third = Third::get(['user_id' => $this->auth->id]);
        $openid = $third->openid;//"oQsFe0q0dlLOZXyo6XiMr4VQHaP4";

        //生成支付订单

        $response = Service::submitOrder($amount, $out_trade_no, $type, $title, $notifyurl, $returnurl, $method, $openid);
        $this->success("请返回网站查看支付结果", $response);
    }

    /**
     * 首页
     *
     */
    public function index()
    {

        $message = $this->request->post('message');
        $modelType = $this->request->post('modelType');

        if($modelType == 7) {
            $apiUrl = 'https://api.openai.com/v1/images/generations';

            $params = json_encode([
                'prompt' => $message,
                "n" => 2,
                "size" => "256x256"
            ]);

        }else {
            $apiUrl = 'https://api.openai.com/v1/completions';
            $apiModel = 'text-davinci-001';
            $params = json_encode([
                'prompt' => $message,
                'model' => $apiModel,
                'temperature' => 0.7,
                'max_tokens' => 256,
                'top_p' => 1,
                'frequency_penalty' => 0,
                'presence_penalty' => 0
            ]);
        }

        $value = \app\common\model\Config::get(['group' => 'config', 'name' => 'user']);
        $userConfg = json_decode($value->value,true);
        $user_id = $this->auth->id;

        $value = \app\common\model\Config::get(['group' => 'basic', 'name' => 'gpt_key']);

        if($message == '') {
            $this->error('请输入问题');
        }

        $api_key = $value->value;
        if($api_key == '') {
            $this->error('请配置key');
        }

        //判断用户是否是会员
        $user = \app\admin\model\User::get($user_id);

        //普通用户限制查找次数
        if($user['level'] == 0 ){
            //判断用户每天查找次数
            $find_num = $userConfg['find_num'];
            //获取用户分享免费查找次数
            $num = $user['find_num'];
            //不符合提示
            $starttime = Date::unixtime('day');
            $endtime = Date::unixtime('day', 0, 'end');
            $ret = Db("user_find")->where('createtime', 'between time', [$starttime, $endtime])
                ->where('user_id' , $user_id)
                ->value('views');

            if($ret && $ret >= $find_num) {
                if ($user->find_num >= ($ret - $find_num) ) {
                    //扣除用户查询次数
                    $user->find_num -= 1;
                    $user->save();
                }else {
                    $this->error('查询次数已用完');
                }
            }
        }

        $ch  = curl_init();

        curl_setopt_array($ch, [
            CURLOPT_URL => $apiUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => 0,
            CURLOPT_FOLLOWLOCATION => 1,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $api_key
            ],
            CURLOPT_POSTFIELDS => $params
        ]);
        $response = curl_exec($ch);
        curl_close($ch);
        $response = json_decode($response);

        $model = UserFind::get(['user_id' => $user_id]);
        if($model) {
            $model->views++;
            $model->save();
        }else {
            UserFind::create(['user_id' => $user_id, 'views' => 1]);
        }

        $this->success('请求成功',$response);
    }

    public function topicList()
    {
        $list = Type::all();
        $arr = [];
        foreach ($list as $key => $value) {
            $queList  = Db("topic")->where('type_id', $value->id)
                ->select();
            $arr[] = [
                'title' => $value->name,
                'message' => $value->message,
                'queList' => $queList,
                'image' => $this->request->domain().$value->image
            ];
        }
        $this->success('请求成功',$arr);
    }
}
